﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using StockTrader.BusinessService.DataContract;
using StockTrader.BusinessService.DataContract.Structure;
using StockTrader.FrontEnd.OrderTracker.DAL;
using StockTrader.FrontEnd.DataContract;
using System.Reflection;
using StockTrader.FrontEnd.OrderTracker.Business;
using System.Deployment.Application;
using System.IO;
using StockTrader.FrontEnd.OrderTracker.Report;
using MySql.Data.MySqlClient;

namespace StockTrader.FrontEnd.OrderTracker
{
    public partial class frmMain : Form
    {
        public List<OrderUI> list = new List<OrderUI>();
        public DateTime lastUpdated = DateTime.Now;

        private DataSet dataset;
        private MySqlDataReader reader;
        private bool IsPublicMode = true;

        private System.Timers.Timer pollTimer = new System.Timers.Timer();
        private System.Timers.Timer trackerTimer = new System.Timers.Timer();
        private System.Timers.Timer alerterTimer = new System.Timers.Timer();

        public frmMain()
        {
            this.Font = SystemFonts.MessageBoxFont;
            Splasher.Status = "Đang khởi động ...";
            InitializeComponent();
            Splasher.Status = "Kết nối tới dữ liệu ...";

            try
            {
                DataAccess da = new DataAccess();
                List<OrderUI> HoOrders = new List<OrderUI>();
                List<OrderUI> HaOrders = new List<OrderUI>();

                if (chkHo.CheckState == CheckState.Checked)
                    HoOrders = da.getHoseOrders();
                if (chkHa.CheckState == CheckState.Checked)
                    HaOrders = da.getHastcOrders();

                Splasher.Status = "Chuẩn bị các tài nguyên khác ...";
                list = MergeOrders(HaOrders, HoOrders);

                MethodInvoker updateUI = delegate
                {
                    string total = list.Count.ToString();
                    if (lblTotal.Text.Equals(total))
                        lblTotal.ForeColor = Color.Green;
                    else
                    {
                        lblTotal.Text = total;
                        lblTotal.ForeColor = Color.Red;
                    }
                };
                if (lblTotal.InvokeRequired)
                    lblTotal.Invoke(updateUI);
                else
                    updateUI();
                lastUpdated = DateTime.Now;

            }
            catch (Exception ex)
            {
                if (ex is MySql.Data.MySqlClient.MySqlException)
                {
                    Splasher.Status = "Lỗi không kết nối được với CSDL.";
                    System.Threading.Thread.Sleep(2000);
                }
                //Splasher.Status = ex.Message;
                MessageBox.Show(ex.Message + ex.StackTrace + ex.InnerException + ex.TargetSite + ex.Source);
                Environment.Exit(1);
            }

            Splasher.Status = "Done";
            Splasher.Close();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {

            pollTimer.Enabled = true;
            pollTimer.Interval = Parameters.ReadInterval;
            pollTimer.Elapsed += new System.Timers.ElapsedEventHandler(PollDataHandler);

            trackerTimer.Enabled = true;
            trackerTimer.Interval = Parameters.UIupdateInterval;
            trackerTimer.Elapsed += new System.Timers.ElapsedEventHandler(TrackerHandler);

            alerterTimer.Enabled = true;
            alerterTimer.Interval = Parameters.CheckDuplicateInterval;
            alerterTimer.Elapsed += new System.Timers.ElapsedEventHandler(AlerterHandler);

            chkAutoUpdate.Checked = Parameters.GridAutoUpdate;

        }

        private void PollDataHandler(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (rbMainBoard.Checked.Equals(true))
                getOrderUpdate();
            else
                getPtOrderUpdate();

            if (chkAutoUpdate.Checked)
                UpdateGrid();

        }

        private void TrackerHandler(object sender, System.Timers.ElapsedEventArgs e)
        {
            MethodInvoker updateUIState = delegate
            {
                int updateSince = (DateTime.Now - lastUpdated).Seconds + 1;
                this.lblUpdateSince.Text = updateSince.ToString();
                if (updateSince < 10)
                    lblUpdateSince.ForeColor = Color.Green;
                else
                    lblUpdateSince.ForeColor = Color.Red;
            };
            if (lblLegend1.InvokeRequired)
            {
                lblUpdateSince.Invoke(updateUIState);
            }
            else
                updateUIState();
        }

        private void AlerterHandler(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                List<OrderUI> orders = new List<OrderUI>();
                List<OrderUI> ordersFault = new List<OrderUI>();
                List<OrderUI> HoOrders = new List<OrderUI>();
                List<OrderUI> HaOrders = new List<OrderUI>();
                DataAccess da = new DataAccess();

                Filter flt = new Filter();

                HoOrders = da.getHoseOrders();
                HaOrders = da.getHastcOrders();
                orders = MergeOrders(HaOrders, HoOrders);
                ordersFault = flt.ordersFault(orders);

                MethodInvoker updateGrid = delegate
                {
                    this.grvAlert.DataSource = convert2Table<OrderUI>(ordersFault);
                    if (ordersFault.Count > 0)
                        setAlerterGridLayout();
                };
                if (grvAlert.InvokeRequired)
                    grvAlert.BeginInvoke(updateGrid);
                else
                    updateGrid();
            }
            catch
            {
                return;
            }
        }

        private void setAlerterGridLayout()
        {
            grvAlert.Columns["AccountNo"].Width = 86;
            grvAlert.Columns["CancelDetail"].Visible = false;
            grvAlert.Columns["MValue"].Visible = false;
            grvAlert.Columns["AveragePrice"].Visible = false;
            grvAlert.Columns["PriceChange"].Visible = false;
            grvAlert.Columns["Price"].Visible = false;
            grvAlert.Columns["AccountNoChange"].Visible = false;
            grvAlert.Columns["Market"].Visible = false;
            grvAlert.Columns["OrderNo"].Visible = false;

            grvAlert.Sort(grvAlert.Columns["Time"], ListSortDirection.Descending);

        }

        private void getOrderUpdate()
        {
            try
            {
                DataAccess da = new DataAccess();
                List<OrderUI> HoOrders = new List<OrderUI>();
                List<OrderUI> HaOrders = new List<OrderUI>();

                if (chkHo.Checked)
                    HoOrders = da.getHoseOrders();
                if (chkHa.Checked)
                    HaOrders = da.getHastcOrders();

                list = MergeOrders(HaOrders, HoOrders);
                MethodInvoker updateUI = delegate
                {
                    string total = list.Count.ToString("N0");
                    if (lblTotal.Text.Equals(total))
                        lblTotal.ForeColor = Color.Green;
                    else
                    {
                        lblTotal.Text = total;
                        lblTotal.ForeColor = Color.Red;
                    }
                };
                if (lblTotal.InvokeRequired)
                    lblTotal.Invoke(updateUI);
                else
                    updateUI();
                lastUpdated = DateTime.Now;
            }
            catch 
            {
                return;
            }
        }

        private void getPtOrderUpdate()
        {
            try
            {
                DataAccess da = new DataAccess();
                List<OrderUI> HoOrders = new List<OrderUI>();
                List<OrderUI> HaOrders = new List<OrderUI>();

                if (chkHo.CheckState == CheckState.Checked)
                    HoOrders = da.getHosePtOrders();
                if (chkHa.CheckState == CheckState.Checked)
                    HaOrders = da.getHastcPtOrders();

                list = MergeOrders(HaOrders, HoOrders);
                MethodInvoker updateUI = delegate
                {
                    string total = list.Count.ToString("N0");
                    if (lblTotal.Text.Equals(total))
                        lblTotal.ForeColor = Color.Green;
                    else
                    {
                        lblTotal.Text = total;
                        lblTotal.ForeColor = Color.Red;
                    }
                };
                if (lblTotal.InvokeRequired)
                    lblTotal.Invoke(updateUI);
                else
                    updateUI();
            }
            catch 
            {
                return;
            }
            finally
            {
                lastUpdated = DateTime.Now;
            }
        }

        private List<OrderUI> MergeOrders(List<OrderUI> orders1, List<OrderUI> orders2)
        {
            try
            {
                List<OrderUI> mergedlist = new List<OrderUI>();
                mergedlist.AddRange(orders1);
                mergedlist.AddRange(orders2);
                return mergedlist;
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }

        private void UpdateGrid()
        {
            try
            {
                Filter flt = new Filter();
                List<OrderUI> listFiltered = new List<OrderUI>();

                #region Para builder
                string accountNo = txtAccountNo.Text;
                string side = txtSide.Text;
                string symbol = txtSymbol.Text;
                #endregion
                DALclient client = new DALclient();
                List<string> blackList = client.getVipAccount();

                if (IsPublicMode)
                    listFiltered = flt.ordersFilter(list, accountNo, side, symbol, blackList);
                else
                    listFiltered = flt.ordersFilter(list, accountNo, side, symbol);

                MethodInvoker updateGridAsync = delegate
                {
                    updateSummary(listFiltered);
                    grvOrders.DataSource = convert2Table<OrderUI>(listFiltered);
                    if (listFiltered.Count > 0)
                        setOrderGridLayout(grvOrders);
                    if (DateTime.Now.Hour >= 11)
                        chkAutoUpdate.Checked = false;
                };
                if (grvOrders.InvokeRequired || chkAutoUpdate.InvokeRequired)
                    grvOrders.Invoke(updateGridAsync);
                else
                    updateGridAsync();
                //grvOrders.Focus();
            }
            catch (System.Exception e)
            {
                MessageBox.Show(e.Message);
                return;
            }

        }

        private void updateSummary(List<OrderUI> listFiltered)
        {
            try
            {
                decimal matchvalue = 0;
                decimal matchvolume = 0;
                foreach (OrderUI fltr in listFiltered)
                {
                    matchvalue += fltr.MValue;
                    matchvolume += fltr.MVolume;
                }

                if ((list != null) && (listFiltered != null))
                {
                    lblFiltered.Text = listFiltered.Count.ToString();
                    lblTotal.Text = list.Count.ToString();
                }
                else
                {
                    lblFiltered.Text = "0";
                    lblFiltered.Text = "0";
                    MessageBox.Show("Chưa có dữ liệu.");
                }
                lblMatchValue.Text = matchvalue.ToString("N0");
                lblMatchVolume.Text = matchvolume.ToString("N0");
            }
            catch 
            {
                return;
            }
        }

        private void setOrderGridLayout(DataGridView grvOrders)
        {
            grvOrders.Columns["Time"].HeaderText = "Thời gian";
            grvOrders.Columns["Time"].DisplayIndex = 0;

            grvOrders.Columns["OrderNo"].HeaderText = "Số hiệu";
            grvOrders.Columns["OrderNo"].DisplayIndex = 1;

            grvOrders.Columns["Status"].HeaderText = "Trạng thái";
            grvOrders.Columns["Status"].DisplayIndex = 2;

            grvOrders.Columns["Side"].HeaderText = "Loại lệnh";
            grvOrders.Columns["Side"].DisplayIndex = 3;

            grvOrders.Columns["Symbol"].HeaderText = "MCK";
            grvOrders.Columns["Symbol"].DisplayIndex = 4;

            grvOrders.Columns["Volume"].HeaderText = "KL đặt";
            grvOrders.Columns["Volume"].DisplayIndex = 5;
            grvOrders.Columns["Volume"].DefaultCellStyle.Format = "N0";

            grvOrders.Columns["MVolume"].HeaderText = "KL khớp";
            grvOrders.Columns["MVolume"].DisplayIndex = 6;
            grvOrders.Columns["MVolume"].DefaultCellStyle.Format = "N0";

            grvOrders.Columns["Price"].HeaderText = "Giá";
            grvOrders.Columns["Price"].DisplayIndex = 7;

            grvOrders.Columns["PriceChange"].HeaderText = "Sửa giá";
            grvOrders.Columns["PriceChange"].DisplayIndex = 8;

            grvOrders.Columns["AveragePrice"].HeaderText = "Giá TB";
            grvOrders.Columns["AveragePrice"].DisplayIndex = 9;
            grvOrders.Columns["AveragePrice"].DefaultCellStyle.Format = "N1";

            grvOrders.Columns["MValue"].HeaderText = "Giá trị";
            grvOrders.Columns["MValue"].DisplayIndex = 10;
            grvOrders.Columns["MValue"].DefaultCellStyle.Format = "N0";

            grvOrders.Columns["AccountNo"].HeaderText = "Tài khoản";
            grvOrders.Columns["AccountNo"].DisplayIndex = 11;

            grvOrders.Columns["Market"].HeaderText = "Sàn";
            grvOrders.Columns["Market"].DisplayIndex = 12;

            grvOrders.Columns["AccountNoChange"].Visible = false;
            grvOrders.Columns["CancelDetail"].Visible = false;
            grvOrders.Columns["TransDate"].Visible = false;

            //             grvOrders.Columns["AccountNoChange"].HeaderText = "Sửa TK";
            //             grvOrders.Columns["AccountNoChange"].DisplayIndex = 12;


            grvOrders.Sort(grvOrders.Columns["Time"], ListSortDirection.Descending);
        }

        private void grvOrders_SelectionChanged(object sender, EventArgs e)
        {
            if (grvOrders.SelectedRows.Count > 0)
            {
                DataGridViewRow row = grvOrders.SelectedRows[0];
                if (!string.IsNullOrEmpty(row.Cells["orderno"].Value.ToString()))
                {
                    foreach (OrderUI order in list)
                    {
                        if (order.OrderNo.Equals(row.Cells["orderno"].Value.ToString()))
                        {
                            this.grvOrderMatch.DataSource = order.MatchedDetail;

                            grvOrderMatch.Columns["Timestamp"].HeaderText = "Thời gian";
                            grvOrderMatch.Columns["OrderNumber"].HeaderText = "Số hiệu";
                            grvOrderMatch.Columns["ConfirmNumber"].HeaderText = "Số XN";
                            grvOrderMatch.Columns["MAccount"].HeaderText = "TK đối ứng";
                            grvOrderMatch.Columns["Price"].HeaderText = "Giá";
                            grvOrderMatch.Columns["ValueMatched"].HeaderText = "Giá trị";
                            grvOrderMatch.Columns["Volume"].HeaderText = "KL khớp";
                            grvOrderMatch.Columns["Volume"].DefaultCellStyle.Format = "N0";
                        }
                    }
                }
                else
                    grvOrderMatch.DataSource = null;
            }
            else
                grvOrderMatch.DataSource = null;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            getOrderUpdate();
            UpdateGrid();
        }

        private void txtAccountNo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue.Equals(13))
                UpdateGrid();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Environment.Exit(1);
        }

        private void txtSide_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue.Equals(13))
                UpdateGrid();

            if (e.KeyValue.Equals(122))
                IsPublicMode = false;
            if (e.KeyValue.Equals(123))
                IsPublicMode = true;

        }

        private void txtSymbol_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue.Equals(13))
                UpdateGrid();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            //             try
            //             {
            //                 int[] Columns = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
            //                 string[] Headers = { "Account", "AccountChange", "Side", "Symbol", "Volume", "Price", "PriceChange", "MVolume", "Average", "MValue", "Time", "Status", "OrderNo", "Market" };
            //                 Export ep = new Export("Win");
            // 
            //                 SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            //                 saveFileDialog1.Filter = "Excel|*.xls";
            //                 saveFileDialog1.Title = "Save as Excel file";
            //                 saveFileDialog1.ShowDialog();
            //                 List<OrderUI> listFiltered = new List<OrderUI>();
            //                 Filter flt = new Filter();
            // 
            //                 if (saveFileDialog1.FileName != "")
            //                 {
            //                     listFiltered = flt.ordersFilter(list, txtAccountNo.Text, txtSide.Text, txtSymbol.Text);
            //                     System.Data.DataTable rst = convert2Table<OrderUI>(listFiltered);
            //                     ep.ExportDetails(rst, Columns, Headers, Export.ExportFormat.Excel, saveFileDialog1.FileName);
            //                     MessageBox.Show("LoL. Xong rồi, có thế chứ.", "WoW!");
            //                 }
            //             }
            //             catch (Exception ex)
            //             {
            //                 MessageBox.Show(ex.Message, "Oops!");
            //             }
            Filter flt = new Filter();
            List<OrderUI> listFiltered = new List<OrderUI>();

            #region Para builder
            string accountNo = txtAccountNo.Text;
            string side = txtSide.Text;
            string symbol = txtSymbol.Text;
            #endregion
            try
            {
                listFiltered = flt.ordersReport(list, accountNo, side, symbol);

                if (listFiltered.Count > 0)
                {
                    AccBook rptAcc = new AccBook();
                    rptAcc.Load(Application.StartupPath + "\\Report\\AccBook.rpt");
                    rptAcc.SetDataSource(listFiltered);

                    frmReport report = new frmReport(rptAcc);
                    report.Show();
                }
                else
                    MessageBox.Show("Chẳng có gì để in cả!?", "Oops!");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "Oops!");
                return;
            }
        }

        private void chkHo_CheckedChanged(object sender, EventArgs e)
        {
            if (rbMainBoard.Checked)
                getOrderUpdate();
            else
                getPtOrderUpdate();
            UpdateGrid();
            updateSummary(list);
        }

        private void chkHa_CheckedChanged(object sender, EventArgs e)
        {
            if (rbMainBoard.Checked)
                getOrderUpdate();
            else
                getPtOrderUpdate();
            UpdateGrid();
            updateSummary(list);
        }

        public static DataTable convert2Table<T>(List<T> list)
        {
            DataTable table = new DataTable();
            if (list.Count > 0)
            {
                PropertyInfo[] properties = list[0].GetType().GetProperties();
                List<string> columns = new List<string>();
                foreach (PropertyInfo pi in properties)
                {
                    Type t = pi.PropertyType;
                    table.Columns.Add(pi.Name, t);
                    columns.Add(pi.Name);
                }
                foreach (T item in list)
                {
                    object[] cells = getValues(columns, item);
                    table.Rows.Add(cells);
                }
            }
            return table;
        }

        private static object[] getValues(List<string> columns, object instance)
        {
            try
            {
                object[] ret = new object[columns.Count];
                for (int n = 0; n < ret.Length; n++)
                {
                    PropertyInfo pi = instance.GetType().GetProperty(columns[n]);
                    object value = pi.GetValue(instance, null);
                    ret[n] = value;
                }
                return ret;
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }

        private void tclMain_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tclMain.SelectedTab.Name.Equals("tbSummary"))
            {
                //                 MessageBox.Show("Comming soon!");
                //                 tclMain.SelectedTab = tbOps;
                //                 LoadData();
                //                 ShowData();

            }
        }

        private void grvOrders_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex.Equals(2))
                if (e.Value.ToString().Equals("MUA"))
                    grvOrders.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.PaleGreen;
                else
                    grvOrders.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightYellow;

            if (e.ColumnIndex.Equals(8) || e.ColumnIndex.Equals(10) || e.ColumnIndex.Equals(9))
            {
                if (e.Value.ToString().Equals("0"))
                    e.Value = e.CellStyle.NullValue;
            }
        }

        private void CreateShortcut()
        {
            try
            {
                ApplicationDeployment application = ApplicationDeployment.CurrentDeployment;
                if (ApplicationDeployment.IsNetworkDeployed && application.IsFirstRun)
                {
                    Assembly code = Assembly.GetExecutingAssembly();

                    string company = string.Empty;
                    string description = string.Empty;

                    if (Attribute.IsDefined(code, typeof(AssemblyCompanyAttribute)))
                    {
                        AssemblyCompanyAttribute asssemblyCompany =
                            (AssemblyCompanyAttribute)Attribute.GetCustomAttribute(code,
                            typeof(AssemblyCompanyAttribute));

                        company = asssemblyCompany.Company;
                    }

                    if (Attribute.IsDefined(code, typeof(AssemblyDescriptionAttribute)))
                    {
                        AssemblyDescriptionAttribute assemblyDescription =
                            (AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(code,
                            typeof(AssemblyDescriptionAttribute));

                        description = assemblyDescription.Description;

                    }

                    if (!string.IsNullOrEmpty(company) && !string.IsNullOrEmpty(description))
                    {
                        string desktopPath = string.Concat(
                            Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
                            "\\", description, ".appref-ms");

                        string shortcutName = string.Concat(
                            Environment.GetFolderPath(Environment.SpecialFolder.Programs),
                            "\\", company, "\\", description, ".appref-ms");

                        File.Copy(shortcutName, desktopPath, true);
                    }
                }
            }
            catch 
            {
                return;
            }

        }

        private void rbMainBoard_CheckedChanged(object sender, EventArgs e)
        {
            if (rbMainBoard.Checked)
                getOrderUpdate();
            else
                getPtOrderUpdate();
            UpdateGrid();
            updateSummary(list);
        }

        private void LoadData()
        {
            MySqlCommand cmd = new MySqlCommand("select * from orders where transdate>" + dtFromDate.ToString() + "and transdate <" + dtToDate.ToString());
            reader = cmd.ExecuteReader();
            dataset.Tables["Orders"].Clear();
            dataset.Tables["Orders"].Load(reader);
            dataset.Tables["Orders"].PrimaryKey = new DataColumn[] { dataset.Tables["Orders"].Columns["Date"], dataset.Tables["Orders"].Columns["Order_No"] };
            dataset.Tables["Orders"].DefaultView.Sort = "Date, Time DESC";
        }
        private void UpdateData()
        {
            dataset.Tables["Orders"].Load(reader, LoadOption.Upsert);
        }
        private void ShowData()
        {
            grvOrders.DataSource = dataset.Tables["Orders"];
        }

        private void textBox7_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue.Equals(13))
            {
                getOrderSummaryUpdate(dtFromDate.Value, dtToDate.Value);
            }
        }

        private void getOrderSummaryUpdate(DateTime from, DateTime to)
        {
            try
            {
                DataAccess da = new DataAccess();
                List<OrderUI> HoOrders = new List<OrderUI>();
                List<OrderUI> HaOrders = new List<OrderUI>();

                if (chkHo.Checked)
                    HoOrders = da.getHoseOrdersSummary(from, to);
                if (chkHa.Checked)
                    HaOrders = da.getHastcOrdersSummary(from, to);

                list = MergeOrders(HaOrders, HoOrders);
                MethodInvoker updateUI = delegate
                {
                    string total = list.Count.ToString("N0");
                    if (lblTotal.Text.Equals(total))
                        lblTotal.ForeColor = Color.Green;
                    else
                    {
                        lblTotal.Text = total;
                        lblTotal.ForeColor = Color.Red;
                    }
                };
                if (lblTotal.InvokeRequired)
                    lblTotal.Invoke(updateUI);
                else
                    updateUI();
                lastUpdated = DateTime.Now;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void UpdateGridSummary()
        {
            try
            {
                Filter flt = new Filter();
                List<OrderUI> listFiltered = new List<OrderUI>();

                #region Para builder
                string accountNo = txtAccount1.Text;
                string side = txtSide1.Text;
                string symbol = txtSymbol1.Text;
                #endregion

                List<string> blackList = getBlackList("blackList.txt");
                if (IsPublicMode)
                    listFiltered = flt.ordersFilter(list, accountNo, side, symbol, blackList);
                else
                    listFiltered = flt.ordersFilter(list, accountNo, side, symbol);

                MethodInvoker updateGridAsync = delegate
                {
                    grvOrderSummary.DataSource = convert2Table<OrderUI>(listFiltered);
                    if (listFiltered.Count > 0)
                        setOrderSummaryGridLayout(grvOrderSummary);
                    if (DateTime.Now.Hour >= 11)
                        chkAutoUpdate.Checked = false;
                };
                if (grvOrderSummary.InvokeRequired)
                    grvOrderSummary.Invoke(updateGridAsync);
                else
                    updateGridAsync();
                //grvOrders.Focus();
            }
            catch (System.Exception e)
            {
                MessageBox.Show(e.Message);
            }

        }

        private void txtSymbol_KeyDown_1(object sender, KeyEventArgs e)
        {
            if (e.KeyValue.Equals(13))
            {
                getOrderSummaryUpdate(dtFromDate.Value, dtToDate.Value);
                UpdateGridSummary();
            }
        }

        private void txtSide_KeyDown_1(object sender, KeyEventArgs e)
        {
            if (e.KeyValue.Equals(13))
            {
                getOrderSummaryUpdate(dtFromDate.Value, dtToDate.Value);
                UpdateGridSummary();
            }
        }

        private void txtAccountNo_KeyDown_1(object sender, KeyEventArgs e)
        {
            if (e.KeyValue.Equals(13))
            {
                getOrderSummaryUpdate(dtFromDate.Value, dtToDate.Value);
                UpdateGridSummary();
            }
        }

        private void setOrderSummaryGridLayout(DataGridView grv)
        {
            grv.Columns["Time"].HeaderText = "Thời gian";
            grv.Columns["Time"].DisplayIndex = 0;

            //             grv.Columns["OrderNo"].HeaderText = "Số hiệu";
            //             grv.Columns["OrderNo"].DisplayIndex = 1;

            grv.Columns["Status"].HeaderText = "Trạng thái";
            grv.Columns["Status"].DisplayIndex = 2;

            grv.Columns["Side"].HeaderText = "Loại lệnh";
            grv.Columns["Side"].DisplayIndex = 3;

            grv.Columns["Symbol"].HeaderText = "MCK";
            grv.Columns["Symbol"].DisplayIndex = 4;

            grv.Columns["Volume"].HeaderText = "KL đặt";
            grv.Columns["Volume"].DisplayIndex = 5;
            grv.Columns["Volume"].DefaultCellStyle.Format = "N0";

            grv.Columns["MVolume"].HeaderText = "KL khớp";
            grv.Columns["MVolume"].DisplayIndex = 6;
            grv.Columns["MVolume"].DefaultCellStyle.Format = "N0";

            grv.Columns["Price"].HeaderText = "Giá";
            grv.Columns["Price"].DisplayIndex = 7;

            grv.Columns["PriceChange"].HeaderText = "Sửa giá";
            grv.Columns["PriceChange"].DisplayIndex = 8;

            grv.Columns["AveragePrice"].HeaderText = "Giá TB";
            grv.Columns["AveragePrice"].DisplayIndex = 9;
            grv.Columns["AveragePrice"].DefaultCellStyle.Format = "N1";

            grv.Columns["MValue"].HeaderText = "Giá trị";
            grv.Columns["MValue"].DisplayIndex = 10;
            grv.Columns["MValue"].DefaultCellStyle.Format = "N0";

            grv.Columns["AccountNo"].HeaderText = "Tài khoản";
            grv.Columns["AccountNo"].DisplayIndex = 11;

            grv.Columns["Market"].HeaderText = "Sàn";
            grv.Columns["Market"].DisplayIndex = 12;

            grv.Columns["AccountNoChange"].Visible = false;
            grv.Columns["CancelDetail"].Visible = false;
            grv.Columns["TransDate"].Visible = true;
            grv.Columns["OrderNo"].Visible = false;
            //             grvOrders.Columns["AccountNoChange"].HeaderText = "Sửa TK";
            //             grvOrders.Columns["AccountNoChange"].DisplayIndex = 12;


            grv.Sort(grv.Columns["Time"], ListSortDirection.Descending);
        }

        public List<string> getBlackList(string listFile)
        {
            List<string> blackList = new List<string>();
            try
            {
                StreamReader re = File.OpenText(listFile);
                string input = null;
                while ((input = re.ReadLine()) != null)
                    blackList.Add(input);
                re.Close();
                return blackList;
            }
            catch
            {
                return null;
            }
        }
    }
}
